package com.steven.bio;


import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 一个客户端对应一个线程 accept会阻塞
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8666);
        System.out.println("服务启动");
        while (true){
            //监听，等待连接
            //没有连接的时候会阻塞
           final Socket socket = serverSocket.accept();
            System.out.println("连接到客户端");
            executorService.execute(() -> {
                //客户端通讯
                System.out.println(Thread.currentThread().getName());
                handler(socket);
            });
        }
    }

    //处理类
    @SneakyThrows
    public static void handler(Socket socket){
       byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            //循环读取
            while (true){
                //如果没有数据会阻塞
                int read = inputStream.read(bytes);
                if(read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭连接");
            socket.close();
        }
    }



}
